<template>
  <div class="user" v-if="userStore.role == '管理员'">
    <el-dialog v-model="isShow" :title="operateType == 'add' ? '添加用户' : '编辑用户'" width="56%" :show-close="false">
      <!-- 绑定form标签 form数据 -->
      <CForm :form="form" :formlabel="formlabel" :inline="true" />
      <template #footer>
        <el-button @click="isShow = false">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>

    <div class="table-operation">
      <el-input clearable v-model="keywords" placeholder="搜索关键字" />
      <el-button type="primary" :icon="Search" @click="search">搜索</el-button>
      <el-button type="warning" :icon="Plus" @click="add">添加用户</el-button>
      <el-button type="info" :icon="Refresh" @click="getPageData">刷新</el-button>
    </div>

    <div class="user-table">
      <CTable :table-data="tableData" :table-label="tableLabel" :edit="edit" :del="del" :loading="loading" />
    </div>

    <!-- 分页器 -->
    <CPagination :page-info="pageInfo" :handle-current-change="handleCurrentChange"
      :handle-size-change="handleSizeChange" />
  </div>
  <div class="error" v-else>
    <Error_403 />
  </div>
</template>

<script setup lang="ts">
import { Search, Plus, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, defineAsyncComponent } from 'vue';
import CTable from '../../components/CTable.vue';
import CPagination from '../../components/CPagination.vue'
import CForm from '../../components/CForm.vue';
import { getUsersApi, addUserApi, delUserApi, updateUserApi } from '../../api/user'
import { useUserStore } from '../../store/user'
const Error_403 = defineAsyncComponent(() => import('../../components/403.vue'))

const userStore = useUserStore()

const tableLabel = reactive([
  { name: 'nickname', label: '昵称', width: 150 },
  { name: 'username', label: '用户名', width: 150 },
  { name: 'password', label: '密码', width: 150 },
  { name: 'role', label: '角色', width: 150 },
])

let tableData = reactive<any>([])
let keywords = ref('')
let loading = ref(true)

// 分页信息
const pageInfo = reactive({
  // 页面大小
  pageSize: 10,
  // 当前页
  currentPage: 1,
  // 总数据量
  total: 0,
})
function handleSizeChange(val: number) {
  pageInfo.pageSize = val
  getPageData()
}
function handleCurrentChange(val: number) {
  pageInfo.currentPage = val
  getPageData()
}
// 获取页面数据
async function getPageData() {
  loading.value = true
  const res = await getUsersApi(pageInfo)
  console.log(res)
  if (res.data.code == '4003') {
    ElMessage.warning(res.data.msg)
    return
  }
  const pageData = res.data.pageData
  tableData.splice(0)
  tableData.push(...pageData)
  pageInfo.total = res.data.total
  loading.value = false
}
onMounted(() => {
  getPageData()
})

const formlabel = reactive([
  {
    model: "nickname",
    label: "昵称",
    type: "input",
  },
  {
    model: "username",
    label: "用户名",
    type: "input",
  },
  {
    model: "password",
    label: "密码",
    type: "password",
  },
  {
    model: "role",
    label: "角色",
    type: "select",
    opts: [
      {
        label: "管理员",
        value: 'admin',
      },
      {
        label: "训练师",
        value: 'trainer'
      },
      {
        label: "用户",
        value: 'cuser'
      },
    ],
  },
])

let form = ref<any>({})

let isShow = ref(false)
// 判断操作是删除还是修改
let operateType = ref('add')

function add() {
  operateType.value = 'add'
  form.value = {}
  isShow.value = true
}

function edit(row: any) {
  operateType.value = 'edit'
  form.value = row
  isShow.value = true
}

function del(row: any) {
  ElMessageBox.confirm(
    '删除后不可恢复，是否删除',
    'Warning',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const { id } = row
      const res = await delUserApi(id)
      if (res.data.msg == '删除成功') {
        ElMessage.success(res.data.msg)
        // 刷新
        getPageData()
      } else {
        ElMessage.warning(res.data.msg)
      }
    })
    .catch(() => {
      ElMessage.info('已取消操作')
    })
}

async function confirm() {
  if (operateType.value == 'add') {
    // 添加
    const res = await addUserApi(form.value)
    ElMessage.success(res.data.msg)
  } else {
    // 修改
    const res = await updateUserApi(form.value);
    ElMessage.success(res.data.msg)
  }
  console.log(form.value)
  isShow.value = false
  getPageData()
}

// 过滤搜索
async function search() {
  await getPageData()
  const filterData = tableData.filter((item: { nickname: string | string[]; }) => {
    return item.nickname.indexOf(keywords.value) !== -1;
  })
  tableData.splice(0)
  tableData.push(...filterData)
  pageInfo.total = tableData.length
  keywords.value = ''
}

</script>

<style scoped lang="less">
</style>